//
//  Category_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/10.
//
//

import UIKit
import UtilCore
import RickonCore
import AddCarCore
import EmptyDataView
import BrandonCore

class Category_Vc: Empty_TVc,AddCarProtocol{
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var typeTableView: UITableView!              //类型表
    
    @IBOutlet weak var goodsList_TableView: UITableView!        //商品列表
    
    @IBOutlet weak var search_Label: UILabel!                   //搜索Label
    
    var test_IsClicked = true                                   //判断是否默认选中(爆款推荐)
    
    var typeArr:[CategoryTypeModel]?{                           //类型数据源
        didSet{
            self.typeTableView.reloadData()
        }
    }
    var goodsArr:[CategoryGoodModel]?{                          //商品数据源
        didSet{
            self.goodsList_TableView.reloadData()
        }
    }
    @IBOutlet weak var search_View: UIView!                     //搜索
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var CategoryTypeVm:GetCategoryTypeVm?                       //获取类型列表
    
    var CategoryGoodListVm:GetCategoryGoodListVm?               //获取商品列表
    
    let hearder = MJRefreshNormalHeader()                       //商品顶部刷新
    
    let footer = MJRefreshAutoNormalFooter()                    //商品底部刷新
    
    var pdid:String?                                            //商品ID
    
    var productModel:ProductModel?                              //SKU_Model
    
    var isrefresh = true                                        //界面展示方式
    
    var name_Message:String?                                    //消息(图片)是否显示小圆点
    
    var OrderNum:OrderNumVm?                                    //消息数量
    
    var GetSku:GetSkuVm?
    
    var isreloadType = false
    
    var defaultKeyWord:String?{
        didSet{
            self.search_Label.text = self.defaultKeyWord
        }
    }
    var placeKeyWork = "请输入您想要的商品"
    
    private lazy var rightBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x:5, y:0, width:30, height:35)
        button.setImage(UIImage.init(named: "xiaoxi-readed", in: SansaCore.bundle, compatibleWith: nil), for: .normal)
        return button
    }()
    
    /****************************Storyboard 绑定方法区域****************************/
    @IBAction func add_JHD(_ sender: UIButton) {
        
        if let _ = AppData.loginedUser{
            if case AppDataState.audited = AppData.appState{
                self.GetSku?.getSKU.onNext("\(goodsArr?[sender.tag].pdid ?? "0")")
            }else{
                _ = "authvalidation".openURL(["isneedlogin":"1"])
            }
        }else{
            _ = "login".openURL()
        }
        
    }
    
    @IBAction func searchClicked(_ sender: AnyObject) {
        self.isrefresh = false
        if let defaultKeyWord = self.defaultKeyWord, defaultKeyWord != placeKeyWork {
            _ = "searchpage".openURL(["keyWord":defaultKeyWord])
        }else{
            _ = "searchpage".openURL()
        }
    }
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshing(_:)), name: NSNotification.Name(AppConfig.notification.defaultKeyWordKey), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(messageCount(_:)), name: NSNotification.Name(rawValue: AppConfig.notification.messagenumKey), object: nil)
    }
    func refreshing(_ notification: NSNotification) {

        self.defaultKeyWord = notification.object as! String?
        
    }
    func messageCount(_ notification: NSNotification){
        
        if notification.object as! Int == 0{
        
            self.rightBtn.setImage(UIImage.init(named: "xiaoxi-readed", in: SansaCore.bundle, compatibleWith: nil),for: .normal)
        }else{
            
            self.rightBtn.setImage(UIImage.init(named: "xiaoxi-unread", in: SansaCore.bundle, compatibleWith: nil), for: .normal)
            
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        _ = "defaultKeyWord".openURL()
        _ = "messagenum".openURL()
        if isrefresh == true{
            self.CategoryTypeVm?.defaultKeyModel_request.onNext()
            self.test_IsClicked = true
            self.CategoryGoodListVm?.pptype = ""
            self.CategoryGoodListVm?.ppturl = ""
            self.CategoryGoodListVm?.ppturlStatus.value = ""
            self.CategoryTypeVm?.GetCategoryType.onNext()
        }else{
            isrefresh = true
        }
    }
    override func customLeftBarButtonItem()  {
        let  rightItem = UIBarButtonItem(customView: self.rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        
        self.goodsList_TableView.dzn_tv_emptyDelegate = self
        self.goodsList_TableView.dzn_tv_emptyDataSource = self
        self.goodsList_TableView.tableFooterView = UIView()
        
        self.goodsList_TableView.showsVerticalScrollIndicator = false
        self.typeTableView.showsVerticalScrollIndicator = false
        setTypeTabelView()
        setGoodsListTableView()
        // 上拉刷新
        hearder.setRefreshingTarget(self, refreshingAction: #selector(Category_Vc.headerRefresh))
        self.goodsList_TableView.mj_header = hearder
        
        // 下拉加载更多
        footer.setRefreshingTarget(self, refreshingAction: #selector(Category_Vc.footerRefresh))
        footer.isAutomaticallyHidden = true
        self.goodsList_TableView.mj_footer = footer
        
        self.search_View.changeBorderColor(Theme.category.homepage_searchbar_bg, cornerRadius: 6.0, borderWidth: 0.5)
        self.search_View.backgroundColor = Theme.category.homepage_searchbar_bg
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        search_Label.normal_fontSize(12)
    }
    func setTypeTabelView(){
        
        self.typeTableView.delegate = self
        self.typeTableView.dataSource = self
    }
    func setGoodsListTableView(){
        self.goodsList_TableView.dataSource = self
        self.goodsList_TableView.delegate = self
    }
    //------
    //下拉加载
    func footerRefresh(){
        self.footer.endRefreshing()
    }
    //---
    //上拉刷新
    func headerRefresh(){
        
        self.hearder.endRefreshing()
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        //获取分类类型列表
        //.-----------------------------------------
        self.CategoryTypeVm = GetCategoryTypeVm()
        
        self.CategoryTypeVm?.backdata.asObserver().subscribe(onNext:{ data in
            
            self.isreloadType = true
            self.typeArr = data
            
            }).addDisposableTo(disposeBag)
        
        self.CategoryTypeVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //-----------------------------------------------
        //获取分类对应的商品
        self.CategoryGoodListVm = GetCategoryGoodListVm(
            input:(
                refreshTriger:  rx.sentMessage(#selector(Category_Vc.headerRefresh)).map { _ in () },
                loadMoreTriger: rx.sentMessage(#selector(Category_Vc.footerRefresh)).map { _ in () }
            )
        )
        
        self.CategoryGoodListVm?
            .backDate
            .asObservable()
            .do(onNext:{[unowned self] _ in
                
                self.errorPageView.isHidden = true
                
            }).subscribe(onNext:{ data in
                
                self.showEmptyView = true
                self.goodsArr = data
                
            }).addDisposableTo(disposeBag)
        
        self.CategoryGoodListVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        //绑定错误
        self.CategoryGoodListVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.CategoryGoodListVm?.refresherror.asObserver().bindTo(self.rx_showerrorpage).addDisposableTo(disposeBag)
        self.errorPageView.reloadSubject.bindTo(self.CategoryGoodListVm!.reloadTrigger).addDisposableTo(disposeBag)
        
        self.errorPageView.reloadSubject.subscribe(onNext:{ _ in
            if self.isreloadType == false{
                self.CategoryTypeVm?.GetCategoryType.onNext()
            }else{
                print("我爱你 ---------")
            }
        }).addDisposableTo(disposeBag)
        
        //判断是否还有数据如果有就继续加载,没有则提示已经展示全部
        self.CategoryGoodListVm?.hasNextPage.asDriver().asObservable().subscribe(onNext:{ hasNextPage in
            if !hasNextPage{
                self.footer.endRefreshingWithNoMoreData()
            }else{
                self.footer.resetNoMoreData()
            }
        }).addDisposableTo(disposeBag)
        
        //======加入铺货单
//        let manageVm = Add_shoppingCartVm()
        
//        self.CategoryGoodListVm?.backSkuDate.asObserver().subscribe(onNext:{ result in
//        
//            self.productModel = result
//            if let model = self.productModel{
//                self.addCar(vc: self, model: model,footerButonType:"jrphd"){ product,osCarts,_ in
////                    self..addcartsSubject.onNext(osCarts)
//                }
//            }
//            
//            }).addDisposableTo(disposeBag)
        
        self.GetSku = GetSkuVm()
        
        self.GetSku?.backSkuDate.asObserver().subscribe(onNext:{ result in
            
            self.addCar(vc: self, model: result,footerButonType:"jrphd"){ product , param,_ in
                self.GetSku?.addcartsSubject.onNext(param["osCarts"] as! NSString)
            }
            
        }).addDisposableTo(disposeBag)
        
        self.GetSku?.addcartsSuccess.subscribe(onNext:{ data in
            
            _ = "orderformbadge".openURL()
            self.view.toastErrorCode(100041002)
            
            
            
        }).addDisposableTo(disposeBag)
        
        self.GetSku?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)

        
        self.OrderNum = OrderNumVm()
        
        self.OrderNum?.backMessage.asObserver().subscribe(onNext:{ result in
            
            
            if result.messagenum == 0{
                
                self.rightBtn.setImage(UIImage.init(named: "xiaoxi-readed", in: SansaCore.bundle, compatibleWith: nil),for: .normal)
                
            }else{
                
                self.rightBtn.setImage(UIImage.init(named: "xiaoxi-unread", in: SansaCore.bundle, compatibleWith: nil), for: .normal)
                
            }
            
            
        }).addDisposableTo(disposeBag)
        
        self.OrderNum?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        self.rightBtn.rx.tap.subscribe(onNext:{ _ in
            
            _ = "message".openURL()
            
            }).addDisposableTo(self.disposeBag)
    }
    //-------------------------------
    //爆款推荐按钮
    func hotBtnClicked(_ sender:UIButton){
        
        test_IsClicked = true
        if let modelArr = typeArr{
            
            for model in modelArr{
                model.isClick = 0
                model.right_type = 0
            }
        }
        self.goodsList_TableView.contentOffset = CGPoint(x: 0,y: 0)
        self.CategoryGoodListVm?.pptype = ""
        self.CategoryGoodListVm?.ppturl = ""
        self.CategoryGoodListVm?.ppturlStatus.value = ""
        self.typeTableView.reloadData()
        
    }
    func defaultClicked(TapGestureRecognizer:UITapGestureRecognizer){
        
        let sender = TapGestureRecognizer.view
        
        self.goodsList_TableView.contentOffset = CGPoint(x: 0,y: 0)
        if let modelArr = typeArr{
            
            for model in modelArr{
                if sender!.tag == model.customIndex{
                    
                    if modelArr[sender!.tag].isClick == 0{
                        
                        modelArr[sender!.tag].isClick = 1
                        modelArr[sender!.tag].IsChangeWhite = 0
                        
                        
                    }else{
                        
                        modelArr[sender!.tag].isClick = 0
                        
                        modelArr[sender!.tag].IsChangeWhite = 0
                        
                        for type in  modelArr[sender!.tag].sonList{
                            
                            type.isclicked = 0
                        }
                        
                        modelArr[sender!.tag].right_type = 1
                        
                    }
                    
                    
                }else{
                    
                    modelArr[model.customIndex].isClick = 0
                    modelArr[model.customIndex].right_type = 0
                    for type in  modelArr[sender!.tag].sonList{
                        type.isclicked = 0
                    }
                }
                
            }
            self.CategoryGoodListVm?.ppturl = modelArr[sender!.tag].ppturl
            self.CategoryGoodListVm?.pptype = modelArr[sender!.tag].pptype
            self.CategoryGoodListVm?.ppturlStatus.value = modelArr[sender!.tag].ppturl
        }
        
        
        test_IsClicked = false
        self.typeTableView.reloadData()
        
    }
}
extension Category_Vc:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView == typeTableView{
            if let modelArr = typeArr{
                return modelArr.count
            }else{
                return 1
            }
        }else{
            if goodsArr?.count != 0{
                return 1
            }else{
                return 0
            }
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == typeTableView{
            if let modelArr = typeArr{
                if modelArr[section].isClick == 1{
                    return modelArr[section].sonList.count
                }else{
                    return 0
                }
            }else{
                return 0
            }
        }else{
            if let modelArr = goodsArr{
                return modelArr.count
            }else{
                return 0
            }
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == typeTableView{
            let cell = tableView.dequeueReusableCell(withIdentifier: "typecell") as! TypeTableView_Message_Cell
            if let modelArr = typeArr{
                
                cell.MessageLabel.text = modelArr[indexPath.section].sonList[indexPath.row].pptname
                modelArr[indexPath.section].sonList[indexPath.row].customIndex = indexPath.row
                
                if modelArr[indexPath.section].sonList[indexPath.row].isclicked == 1{
                    
                    cell.MessageLabel.layer.masksToBounds = true
                    cell.MessageLabel.layer.cornerRadius = 10.5
                    cell.MessageLabel.backgroundColor = Theme.category.hot_Default_Btn()
                    cell.MessageLabel.textColor = UIColor.white
                    
                }else{
                    cell.MessageLabel.backgroundColor = UIColor.clear
                    cell.MessageLabel.textColor = UIColor.black
                }
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Category_Goods_TableViewCell
            cell.add_PHD_Button.tag = indexPath.row
            if let modelArr = goodsArr{
                cell.item = modelArr[indexPath.row]
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableView == typeTableView{
            if let modelArr = typeArr{
                modelArr[section].customIndex = section
            }
            switch section {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "hotcell") as! TypeTableView_Hedear_Hot_Cell
                cell.hotButton.tag = section
                cell.hotButton.addTarget(self, action: #selector(Category_Vc.hotBtnClicked(_:)), for: .touchUpInside)
                if let modelArr = typeArr{
                    cell.hotButton.setTitle("\(modelArr[section].pptname)", for: .normal)
                }
                if test_IsClicked == true{
                    cell.contentView.backgroundColor = UIColor.white
                    cell.hotButton.backgroundColor = Theme.category.hot_Default_Btn()
                    cell.hotButton.setTitleColor(UIColor.white, for: .normal)
                }
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "headercell") as! TypeTableView_Header_Cell
                let tap = UITapGestureRecognizer()
                tap.addTarget(self, action: #selector(Category_Vc.defaultClicked))
                cell.RBG_View.tag = section
                cell.RBG_View.addGestureRecognizer(tap)
                if let modelArr = typeArr{
                    cell.SJX_ImageView.isHidden = modelArr[section].sonList.isEmpty
                    cell.Label_rightWithSJX.constant = modelArr[section].sonList.isEmpty ? -11.5 : 0
                    cell.FL_Label.text = modelArr[section].pptname
                    if modelArr[section].isClick == 1{
                        
                        cell.contentView.backgroundColor = UIColor.white
                        cell.RBG_View.backgroundColor = Theme.category.hot_Default_Btn()
                        cell.FL_Label.textColor = UIColor.white
                        cell.SJX_ImageView.image = UIImage.init(named: "bottom_white", in: SansaCore.bundle, compatibleWith: nil)
                        
                        cell.SJX_imageView_Height.constant = 6.5
                        cell.SJX_ImageView_Width.constant = 11.5

                    }else{
                        
                        if modelArr[section].right_type == 1{
                            cell.contentView.backgroundColor = UIColor.white
                            cell.RBG_View.backgroundColor = Theme.category.hot_Default_Btn()
                            cell.FL_Label.textColor = UIColor.white
                            cell.SJX_ImageView.image = UIImage.init(named: "Right_Icon_Image", in: SansaCore.bundle, compatibleWith: nil)
                        }else{
                            
                        }
                    }
                    if modelArr[section].isClick == 1 && modelArr[section].IsChangeWhite == 1{
                        
                        cell.contentView.backgroundColor = UIColor.white
                        cell.FL_Label.textColor = UIColor.black
                        cell.SJX_ImageView.image = UIImage.init(named: "bottom", in: SansaCore.bundle, compatibleWith: nil)
                        cell.RBG_View.backgroundColor = UIColor.white
                    }
                }
                
                return cell
            }
        }else{
            return nil
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView == typeTableView{
            return 40
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView == typeTableView{
            if let modelArr = typeArr{
                let item = modelArr[indexPath.section]
                for model in item.sonList{
                    if model.customIndex == indexPath.row{
                        
                        item.IsChangeWhite = 1
                        
                        model.isclicked = 1
                        
                    }else{
                        model.isclicked = 0
                    }
                }
                self.CategoryGoodListVm?.ppturl = item.sonList[indexPath.row].ppturl
                self.CategoryGoodListVm?.pptype = item.sonList[indexPath.row].pptype
                self.CategoryGoodListVm?.ppturlStatus.value = item.sonList[indexPath.row].ppturl
            }
            self.typeTableView.reloadData()
        }else{
            //商品列表行点击事件
            if let modelArr = self.goodsArr{
                self.isrefresh = false
                _ = "productdetail".openURL(["pdid":"\(modelArr[indexPath.row].pdid)"])
            }
        }
    }
}
extension Category_Vc:EmptyDataSource{
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        return Theme.getEmptyDesc("该分类，暂无商品！\n换个分类试试吧～")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        return UIImage.init(named: "brandproduct-empty", in: SansaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}
